package com.example.easypoi.service;

import com.example.easypoi.entity.Contract;
import com.example.easypoi.entity.Userdoc;
import com.example.easypoi.util.WordTemplateUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecgframework.poi.cache.WordCache;
import org.jeecgframework.poi.exception.word.WordExportException;
import org.jeecgframework.poi.word.WordExportUtil;
import org.jeecgframework.poi.word.entity.MyXWPFDocument;
import org.jeecgframework.poi.word.parse.ParseWord07;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WordExportService {

    @Autowired
    private WordTemplateUtil wordTemplateUtil;

    public XWPFDocument exportWordWithEntity(String templateName, Map<String, Object> params) {
        try (InputStream is = new ClassPathResource("templates/" + templateName).getInputStream()) {
            MyXWPFDocument document = new MyXWPFDocument(is);
            new ParseWord07().parseWord(document, params);
            return document;
        } catch (Exception e) {
            throw new WordExportException("Word导出失败"+e.toString());
        }

    }

    public XWPFDocument exportWordWithMap(String templatePath, Map<String, Object> params) {
        try {
            MyXWPFDocument document = WordCache.getXWPFDocumen(templatePath);
            new ParseWord07().parseWord(document, params);
            return document;
        } catch (Exception e) {
            throw new WordExportException("Word导出失败"+e.toString());
        }
    }

    public XWPFDocument exportWordWithTable(String templatePath, List<Contract> contracts) {
        Map<String, Object> params = new HashMap<>();
        params.put("title", "合同列表");
        params.put("list", contracts);
        return exportWordWithMap(templatePath, params);
    }

    public XWPFDocument exportWordWithImage(String templatePath, Userdoc user) {
        Map<String, Object> params = new HashMap<>();
        params.put("user", user);
        return exportWordWithMap(templatePath, params);
    }
}